package com.getpebble.android.framework.protocol.inbound;

import com.getpebble.android.bluetooth.protocol.ProtocolMessage;
import com.getpebble.android.common.core.trace.Trace;
import com.getpebble.android.framework.protocol.EndpointId;
import java.nio.ByteBuffer;

public class PblInboundSystemMessage extends PblInboundMessage {
    public static final String TAG = PblInboundSystemMessage.class.getSimpleName();
    private final Type mType;
    private byte[] mTypeData = null;

    public enum Type {
        RECONNECT_STOP((byte) 6),
        RECONNECT_START((byte) 7),
        FIRMWARE_UPDATE_START_ACK((byte) 10);
        
        private byte mCode;

        private Type(byte code) {
            this.mCode = code;
        }

        public byte getCode() {
            return this.mCode;
        }

        public static Type fromCode(byte code) {
            for (Type response : values()) {
                if (response.getCode() == code) {
                    return response;
                }
            }
            return null;
        }
    }

    public PblInboundSystemMessage(ProtocolMessage message) throws IllegalArgumentException {
        super(message);
        ByteBuffer buffer = message.getDataBuffer();
        if (buffer.get() != (byte) 0) {
            throw new IllegalArgumentException("Message did not start with expected zero byte.");
        }
        byte messageType = buffer.get();
        this.mType = Type.fromCode(messageType);
        if (this.mType == null) {
            Trace.warning(TAG, "Received unsupported system message; type: " + messageType);
        }
        int remainingBytes = buffer.remaining();
        if (remainingBytes > 0) {
            byte[] typeData = new byte[remainingBytes];
            buffer.get(typeData);
            this.mTypeData = typeData;
        }
    }

    public Type getType() {
        return this.mType;
    }

    public byte[] getTypeData() {
        return this.mTypeData;
    }

    public EndpointId getId() {
        return EndpointId.SYSTEM_MESSAGE;
    }

    protected int getMinSize() {
        return 2;
    }
}
